﻿
using NLog;

namespace ArticleClientLib
{
    /// <summary>
    /// 软文管理系统 
    /// 中介者
    /// </summary>
    public class AritcleSystem
    {
        ArticleApi api;

        Logger logger = LogManager.GetCurrentClassLogger();

        public AritcleSystem()
        {
            api = new ArticleApi();

            newArticles = new ArticleRootDir(NewRootPath);
            articleRoot = new ArticleRootDir(LocalRootPath);
        }


        public static readonly string NewRootPath = "./newArticles";
        public static readonly string LocalRootPath = "./articleRoot";

        /// <summary>
        /// 新软文
        /// </summary>
        public ArticleRootDir newArticles { get; }

        /// <summary>
        /// 服务端软文
        /// </summary>
        public ArticleRootDir articleRoot { get; }




        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        public (bool pass, string log) Check()
        {
            bool pass = true;
            string log = "";

            var resNewArt = newArticles.Check();
            if (!resNewArt.pass)
            {
                pass = false;
                log += resNewArt.log;
            }

            var resArt = articleRoot.Check();
            if (!resArt.pass)
            {
                pass = false;
                log += resArt.log;
            }

            return (pass, log);
        }





        /// <summary>
        /// 上传所有新软文
        /// </summary>
        public async Task<(bool success, string msg)> UploadNewArticles()
        {
            foreach (Classifly classifly in newArticles.Classiflies)
            {
                foreach (LocalArticle art in classifly.Articles)
                {
                    var res = await UploadSingleNewArticle(classifly, art);
                    if (!res.success)
                    {
                        logger.Error(res.msg);
                        break;
                    }
                }
            }

            logger.Info("软文上传完成。");
            return (true, "");
        }

        /// <summary>
        /// 上传分类下所有软文
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public async Task<(bool success, string msg)> UploadNewArticles(Classifly c)
        {
            foreach (LocalArticle art in c.Articles)
            {
                var res = await UploadSingleNewArticle(c, art);
                if (!res.success)
                {
                    logger.Error(res.msg);
                    break;
                }
            }

            logger.Info($"分类{c.classiflyId}-软文上传完成。");
            return (true, "");
        }


        /// <summary>
        ///  上传单个新软文 
        /// </summary>
        /// <param name="classifly"></param>
        /// <param name="art"></param>
        /// <returns></returns>
        public async Task<(bool success, string msg)> UploadSingleNewArticle(Classifly classifly, LocalArticle art)
        {
            //上传操作
            var upRes = await uploadNewArticle(classifly, art);
            if (!upRes.success)
            {
                //上传失败跳过                
                return (false, $"软文[{art.Dir}]上传失败:{upRes.msg}");
            }
            //填充articleId（上传完成后的必需操作）
            art.ArticleId = upRes.articleId;

            //上传所有图片，包括main.png
            var mainImgRes = await api.ArticleImageUpload(art.mainPng, (long)art.ArticleId);
            if (!mainImgRes.res || !mainImgRes.data.success) return (false, $"main.png上传失败，[{art.Dir}]");

            foreach (var img in art.Images)
            {
                var imgRes = await api.ArticleImageUpload(img, (long)art.ArticleId);
                if (!mainImgRes.res || !mainImgRes.data.success) return (false, $"{img.fileName}上传失败，[{art.Dir}]");
            }

            //添加到Root
            //分类目录创建（不存在时）
            articleRoot.CreateClassiflyIfNotExist(classifly);
            Classifly rootClassifly = articleRoot[classifly.classiflyId];
            rootClassifly.Add(art);

            //从新软文目录中移除
            classifly.Remove(art);

            return (true, $"上传完成:{art.Dir}");
        }


        /// <summary>
        /// 上传一个新软文
        /// </summary>
        /// <param name="classifly"></param>
        /// <param name="art"></param>
        /// <returns></returns>
        async Task<(bool success, string msg, long articleId)> uploadNewArticle(Classifly classifly, LocalArticle art)
        {
            var res = await api.AddGenericArticle(classifly.classiflyId, art);
            if (!res.res) return (false, res.msg, -1);

            ObjectJsonResult jres = res.data;
            if (!jres.success) return (false, jres.msg, -1);

            return (true, $"{art.Article.title} 上传完成", (long)jres.data);
        }

    }
}
